package com.example.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service//注入到spring容器中
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource
    UserMapper userMapper;
    @Override
    public boolean save(User entity) {
        if(StrUtil.isBlank(entity.getName())) {
            entity.setName("普普通通用户");
        }
        if(StrUtil.isBlank(entity.getPassword())) {
            entity.setPassword("12345678");
        }
        if(StrUtil.isBlank(entity.getRole())){
            entity.setRole("用户");
        }
        if(StrUtil.isBlank(entity.getAvatar())){
            entity.setAvatar("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png");
        }
        return super.save(entity);
    }

    public User selectByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);  //等同于where username =#{username}
        return getOne(queryWrapper); //等同于select * from user where username = #{username}
    }

    //验证用户账户是否合法
    public User login(User user) {
        User dbUser = selectByUsername(user.getUsername());
        //根据用户名查询数据库中的用户信息

        if (dbUser == null) {
            //抛出一个自定义异常
            throw new ServiceException("用户名或密码错误");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }
        //生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    //注册时验证
    public User register(User user) {
        User dbUser = selectByUsername(user.getUsername());
        if (dbUser != null) {
            //抛出一个自定义异常
            throw new ServiceException("用户名已存在");
        }
        user.setName(user.getUsername());
        userMapper.insert(user);
        return user;
    }

    //重置密码
    public void resetPassword(User user) {
        User dbUser = selectByUsername(user.getUsername());
        if (dbUser == null) {
            //抛出一个自定义异常
            throw new ServiceException("用户不存在");
        }
        if (!user.getPhone().equals(dbUser.getPhone())) {
            throw new ServiceException("绑定手机号错误");
        }
        dbUser.setPassword("12345678");
        updateById(dbUser);
    }


    public User getByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
}
